package com.keshi.openplatform.monitor.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.keshi.openplatform.monitor.event.EventBean;
import com.keshi.openplatform.monitor.event.EventType;
import com.keshi.openplatform.monitor.feign.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;


import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class AvgJob  implements SimpleJob {
    @Autowired
    private ApplicationContext context;

    @Autowired
    private SearchService searchService;

    private SimpleDateFormat simpleDateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //每个服务的阈值其实可以保存在服务路由信息中,此处为了简化代码编写,我们使用本地写死
    private static Map<String, Integer> maxAvgTimeMap = new HashMap<>();

    static {
        maxAvgTimeMap.put("order.get", 10);
        maxAvgTimeMap.put("order.cancel", 90);

    }

    @Override
    public void execute(ShardingContext shardingContext) {



        //我们当前的任务是看看平均时间有没有超出阈值
        //阈值在哪?
        //我们的任务是每隔10秒执行一次,所以我们要做的事情是拿到当前时间,减去10秒,作为开始时间,然后去查询这个时间范围的平均值
        Instant now = Instant.now();
        //因为es所在的服务器不是中国时区,所以会有8小时的误差
        Date to = Date.from(now.plusSeconds(-3600*8));
        Date from = Date.from(now.plusSeconds(-3600 * 8 - 10));

        Map<String, Integer> apiCountAndAvg = searchService.statApiCountAndAvg(simpleDateFormate.format(from), simpleDateFormate.format(to));
        for (Map.Entry<String, Integer> entry : apiCountAndAvg.entrySet()) {
            String key = entry.getKey();//服务的名字
            Integer avg = entry.getValue();//平均时间
            Integer maxValue = maxAvgTimeMap.get(key);//获取我们当前服务允许的阈值

            if (avg < maxValue) {
                System.err.println("服务" + key + "没有超出阈值");

            }else{
                System.err.println("服务" + key + "超出阈值,阈值为" + maxValue + "  当前为:" + avg);
                //告警,通知开发或者维护人员,但是问题是我们的通知方式是什么,可能是邮件,可能是电话,可能是短信,可能是app,可能是以上几个同时
                EventBean eventBean = new EventBean();
                eventBean.setMsg("服务" + key + "超出阈值,阈值为" + maxValue + "  当前为:" + avg);
                eventBean.setEventType(EventType.OVERTIME);
                context.publishEvent(eventBean);

            }
        }

    }
}
